# coding=utf-8
import datetime
import json
import re
from urllib import parse
import hashlib
import os
import configparser
import requests
import ast

path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config = configparser.ConfigParser()
config_token = configparser.RawConfigParser()
config_token.read(path + '/config/cookie.ini', encoding='utf-8')
config.read(path + '/config/cookie.ini', encoding='utf-8')
config.read(path + '/config/config.ini', encoding='utf-8')


class Headers:

    def getheader(self, pathurl):
        if '?' not in pathurl:
            pass
        else:
            pathurl = pathurl.split("?")[0]

        caller = config.get('testHEADER', 'caller')
        secret = config.get('testHEADER', 'secret')
        result1 = re.compile(r"\/([^\/]*)\/(v\d+|\d\.\d)\/(.+)")
        result2 = result1.search(pathurl)
        contextPath = result2[1]
        version = result2[2]
        requestPath = result2[3]

        if requestPath.endswith('/'):
            requestPath = requestPath[:-1]
        tempArray = requestPath.split("/")
        requestPath = ""
        i = 0
        for k in tempArray:
            if tempArray[i] != "":
                requestPath = requestPath + "/" + parse.quote(tempArray[i])
            i = i + 1
        type = 'application/json;charset=utf-8'
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        encode = secret + "callerService" + caller + "contextPath" + contextPath + "requestPath" + requestPath + "timestamp" + time + "v" + version + secret
        sign = hashlib.md5(encode.encode(encoding='utf-8')).hexdigest().upper()

        reheader = {'Content-Type': type, 'X-Caller-Service': caller, 'X-Caller-Timestamp': time, 'X-Caller-Sign': sign}
        return reheader


class Partner:

    # 线上平台（淘宝、京东、有赞、微信）
    def patner_quota(self, url, relation, header):
        if relation == 'COMMON':
            return Headers().getheader(url)
        elif relation == 'mg':
            return GetToken().getToken()
        elif relation == 'pcrm':
            common = Headers().getheader(url)
            common['x-token'] = GetToken().pcrm_token()
            return common
        elif relation == 'None':
            return None
        elif relation == 'HCOMM':
            common = Headers().getheader(url)
            head = eval(header)
            hcom = {**common, **head}
            return hcom
        else:
            return eval(header)


# mg服务获取鉴权的token
class GetToken:
    def getToken(self):
        global x_token
        type = 'application/json;charset=utf-8'
        header_token = {'Content-Type': type}
        land_url = config_token.get('testcookieconf', 'url')
        land_params = config_token.get('testcookieconf', 'params')
        land_params = ast.literal_eval(land_params)
        land_id = config_token.get('testcookieconf', 'cookies')
        land_id = ast.literal_eval(land_id)
        rs = requests.session()
        r = rs.post(land_url, data=land_params, cookies=land_id)
        r_dict = r.json()
        if 'id' in r_dict.keys():
            x_token = r_dict['id']
        header_token['x-token'] = x_token
        return header_token